package com.example.admin.controller;

import com.example.admin.service.CategoryService;

import com.example.xo.pojo.Category;
import com.example.xo.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 992c
 */
@RestController
@RequestMapping("category")
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @PostMapping("add")
    //@RequesBody代表从返回对象中获取数据，并自动装载
    public Result add(@RequestBody Category category){
        if(category.getCategoryName().length()>20){
            log.info("分类{}字符个数超过20");
            return Result.error();
        }
        if (category.getCategoryName()==null || category.getCategoryName().trim().length()==0){
            log.info("分类的名字不能为空");
        }

        return Result.success(categoryService.add(category));
//        boolean add = categoryService.add(category);
//        return Result.success(add);
    }
    @GetMapping("findAll")
    public Result findAll(){
        List<Category> arr=categoryService.findAll();
        for (Category category : arr) {
            log.info("{}",category);
        }
        return Result.success(arr);

    }
    @GetMapping("{id}")
    //@PathVariable 表示从路径获取参数
    public Result findById(@PathVariable String id){

        Category byId = categoryService.findById(id);
        log.info("查询的id{}",byId);
        return Result.success(byId);
    }
    @GetMapping("findByName/{name}")
    public Result findByNameTest(@PathVariable String name){
        Category byName = categoryService.findByName(name);
        log.info("查询的名字{}",byName);
        return Result.success(byName);
    }
    @PutMapping("update")
    public Result update(@RequestBody Category category){
        //如果用户输入的名字大于20，就返回error错误。
        if (category.getCategoryName().length()>20){
            log.info("分类名长度过长");
            return Result.error();
        }if (category.getCategoryName()==null || category.getCategoryName().trim().length()==0){
            log.info("分类的名字不能为空");
        }
        if(category.getCategoryName().equals(category.getCategoryName())){
            log.info("分类名不能重复");
            return Result.error();
        }
        boolean res = categoryService.update(category);
        log.info("修改的信息{}",res);
        return Result.success(res);

    }
    @DeleteMapping("delete/{id}")
    public Result delete(@PathVariable String id){

        boolean b = categoryService.deleteById(id);
        log.info("删除的id是{}",b);
        return Result.success(b);
    }

}
